
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#include <thread>

const int kServerPort = 1111;

int main(int argc, const char* argv[]) {
  int server_port = 0;
  if (argc == 1)
    server_port = kServerPort;
  else
    server_port = atoi(argv[1]);
  int sock = socket(AF_INET, SOCK_STREAM, 0);
  if (sock < 0) {
    printf("socket error(%d):%s\n", errno, strerror(errno));
    return 0;
  }

  printf("sock:%d\n", sock);
  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr =
      (argc == 3 ? inet_addr(argv[2]) : inet_addr("127.0.0.1"));
  addr.sin_port = htons(server_port);
  printf("connect to port %d\n", server_port);
  if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
    printf("connect error(%d):%s\n", errno, strerror(errno));
    return 0;
  } else {
    printf("connect success\n");

    for (int i = 0; i < 1000; i++) {
      char msg[1024 * 1024];
      snprintf(msg, sizeof(msg), "hello server%d\n", i + 1);
      ssize_t n = write(sock, msg, sizeof(msg));
      printf("write %ld bytes.\n", n);
      std::this_thread::sleep_for(std::chrono::seconds(1));
    }
  }

  // char buff[1024];
  // printf("read...\n");
  // ssize_t n = read(sock, buff, sizeof(buff));
  // printf("read %ld bytes, close\n", n);
  // close(sock);  // read完再close，不会表现为意外断开

  std::this_thread::sleep_for(std::chrono::seconds(3));
  printf("return!\n");
}
